<template>
	<view class="content-box">
		<!-- 顶部金额显示 -->
		<view class="header-section">
			<view class="title-row">
				<text class="title">{{ t('quantify.lhje') }}</text>
				<view class="eye-toggle" @click="toggleEyeStatus">
					<image :src="`/static/icon/${eyeStatus ? 'eye-open' : 'eye-close'}.svg`" mode="aspectFit"></image>
				</view>
			</view>
			<view class="amount-row">
				<text class="amount" v-if="!loading">{{ eyeStatus ? amount : '******' }}</text>
				<text class="amount loading-text" v-else>加载中...</text>
				<text class="unit">USDT</text>
			</view>
			<view class="stats-row">
				<view class="stat-item">
					<view class="dot green"></view>
					<text class="stat-label">{{ t('quantify.jr') }}:</text>
					<text class="stat-value">{{ todayProfit }}</text>
				</view>
				<view class="stat-item">
					<view class="dot orange"></view>
					<text class="stat-label">{{ t('quantify.zj') }}:</text>
					<text class="stat-value">{{ totalProfit }}</text>
				</view>
			</view>
			<!-- 特点介绍 -->
			<view class="features-section">
				<view class="feature-item">
					<image class="feature-icon" src="/static/icon/zjaq.svg" mode="aspectFit"></image>
					<text class="feature-text">{{ t('quantify.zjaq') }}</text>
				</view>
				<view class="feature-item">
					<image class="feature-icon" src="/static/icon/czjd.svg" mode="aspectFit"></image>
					<text class="feature-text">{{ t('quantify.czjd') }}</text>
				</view>
				<view class="feature-item">
					<image class="feature-icon" src="/static/icon/sywd.svg" mode="aspectFit"></image>
					<text class="feature-text">{{ t('quantify.sywd') }}</text>
				</view>
			</view>
		</view>



		<!-- 市场切换 -->
		<view class="market-tabs">
			<view class="tab-item" :class="{ active: activeTab === 'beginner' }" @click="switchTab('beginner')">
				{{ t('quantify.xssc') }}
			</view>
			<view class="tab-item" :class="{ active: activeTab === 'professional' }" @click="switchTab('professional')">
				{{ t('quantify.zysc') }}
			</view>
			<view class="bottom-border"></view>
		</view>

		<!-- 新手市场列表 -->
		<view class="market-list" v-if="activeTab === 'beginner'">
			<view class="market-item new-market-item" v-for="(item, index) in beginnerMarket" :key="'beginner-'+index"
				@click="goDetail(item)">
				<view class="item-left new-left">
					<view class="name-box">
						<view class="">
							<image class="item-image" :src="item.coverImage" mode="aspectFit"></image>
						</view>
						<view class="item-name">{{ item.name }}</view>
					</view>
					<view class="item-info">
						<view class="progress-container">
							<text class="progress-text">{{ t('quantify.jd') }}</text>
							<view class="progress-bar">
								<view class="progress-fill" :style="{width: item.progress + '%'}"></view>
							</view>
							<text class="progress-percent">{{ Math.round(item.progress) }}%</text>
						</view>
						<text class="item-limit">{{ t('quantify.xz') }}: {{ item.limit }}</text>
					</view>
				</view>
				<view class="item-right new-right">
					<text class="item-profit"
						:class="{'positive': item.profit > 0}">{{ item.profit > 0 ? '+' : '' }}{{ item.profit }}%
					</text>
					<view class="item-arrow">
						<image src="/static/image/quantify/right.svg" mode="aspectFit"></image>
					</view>
				</view>
			</view>
		</view>

		<!-- 专业市场列表 -->
		<view class="market-list" v-if="activeTab === 'professional'">
			<view class="market-item professional" v-for="(item, index) in professionalMarket" :key="'professional-'+index"
				@click="goDetail(item)">
				<view class="item-left">
					<view class="name-box">
						<image class="item-image" :src="item.coverImage" mode="aspectFit"></image>
						<view class="item-name">{{ item.name }}</view>
					</view>
					<view class="item-info">
						<view class="progress-container">
							<text class="progress-text">{{ t('quantify.jd') }}</text>
							<view class="progress-bar">
								<view class="progress-fill" :style="{width: item.progress + '%'}"></view>
							</view>
							<text class="progress-percent">{{ Math.round(item.progress) }}%</text>
						</view>
						<text class="item-limit">{{ t('quantify.xz') }}: {{ item.limit }}</text>
					</view>
				</view>
				<view class="item-right">
					<text class="item-profit"
						:class="{'positive': item.profit > 0}">{{ item.profit > 0 ? '+' : '' }}{{ item.profit }}% </text>
					<view class="item-arrow">
						<image src="/static/image/quantify/navigation.svg" mode="aspectFit"></image>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部tabbar -->
		<tabbar :currentTab="2"></tabbar>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		useI18n
	} from 'vue-i18n';
	import { investApi } from '@/utils/api.js';
	
	const {
		t,
		locale
	} = useI18n();

	// 金额显示状态
	const eyeStatus = ref(true);
	const amount = ref('0.00'); // 策略资金，从API获取
	const todayProfit = ref('0.00'); // 今日收益，从API获取
	const totalProfit = ref('0.00'); // 累计收益，从API获取
	const loading = ref(false);

	// 获取收益数据
	const getProfitData = async () => {
		try {
			loading.value = true;
			const response = await investApi.getProfit();
			if (response.code === 0 && response.data) {
				const data = response.data;
				// 更新收益数据
				todayProfit.value = data.todayProfit ? data.todayProfit.toFixed(2) : '0.00';
				totalProfit.value = data.totalProfit ? data.totalProfit.toFixed(2) : '0.00';
				amount.value = data.totalAmount ? data.totalAmount.toFixed(2) : '0.00';
			} else {
				// API返回错误
				console.error('获取收益数据失败:', response.msg || '未知错误');
				uni.showToast({
					title: response.msg || '获取收益数据失败',
					icon: 'none',
					duration: 2000
				});
			}
		} catch (error) {
			console.error('获取收益数据失败:', error);
			// 网络错误或其他异常
			uni.showToast({
				title: '网络连接失败，请检查网络',
				icon: 'none',
				duration: 2000
			});
			// 使用默认值
			todayProfit.value = '0.00';
			totalProfit.value = '0.00';
			amount.value = '0.00';
		} finally {
			loading.value = false;
		}
	};

	// 切换金额显示状态
	const toggleEyeStatus = () => {
		eyeStatus.value = !eyeStatus.value;
	};
	
	const goDetail = (item) => {
		// 获取产品id，优先使用originalData中的id，如果没有则使用item.id
		const productId = item.originalData?.id || item.id;
		if (!productId) {
			uni.showToast({
				title: '产品信息错误',
				icon: 'none',
				duration: 2000
			});
			return;
		}
		
		uni.navigateTo({
			url: `/pages/quantify/details?id=${productId}`
		})
	};
	// 产品名称截取函数，最多显示8个字符，超出用省略号代替
	const truncateProductName = (name) => {
		if (!name) return '';
		if (name.length <= 15) {
			return name;
		}
		return name.substring(0, 15) + '...';
	};

	// 格式化投资限额显示
	const formatInvestLimit = (minAmount, maxAmount) => {
		if (!minAmount && !maxAmount) return '100-500';
		if (!maxAmount) return `${minAmount}+`;
		if (!minAmount) return `≤${maxAmount}`;
		return `${minAmount}-${maxAmount}`;
	};

	// 计算投资进度百分比
	const calculateProgress = (currentScale, totalScale) => {
		if (!totalScale || totalScale === 0) return 0;
		const progress = (currentScale / totalScale) * 100;
		return Math.min(Math.max(progress, 0), 100); // 确保在0-100之间
	};

	// 获取投资品分页数据
	const getProductsPage = async (categoryId) => {
		try {
			const params = {
				categoryId: categoryId,
				pageNo: 1,
				pageSize: 10
			};
			const response = await investApi.getProductsPage(params);
			if (response.code === 0 && response.data) {
				const data = response.data;
				// 根据API返回的数据结构更新市场数据
				if (data.list && Array.isArray(data.list)) {
					const products = data.list.map(item => {
						// 计算投资进度
						const progressPercent = calculateProgress(item.currentTotalScale, item.totalScale);
						
						return {
							id: item.id,
							name: truncateProductName(item.titleZh || item.title || 'Helmet #1005'), // 产品名称，限制6字符
							coverImage: item.image || '/static/icon/bg5.png', // 封面图片
							progress: progressPercent, // 进度百分比
							limit: formatInvestLimit(item.minAmount, item.maxAmount), // 投资限额
							profit: item.rate ? parseFloat(item.rate).toFixed(1) : 1.5, // 收益率保持原值
							// 原始数据保留
							originalData: {
								id: item.id,
								titleZh: item.titleZh,
								rate: item.rate,
								minAmount: item.minAmount,
								maxAmount: item.maxAmount,
								currentTotalScale: item.currentTotalScale,
								totalScale: item.totalScale,
								image: item.image,
								status: item.status,
								categoryId: item.categoryId
							}
						};
					});
					
					// 根据categoryId更新对应的市场数据
					if (categoryId === 1) {
						beginnerMarket.value = products;
					} else if (categoryId === 2) {
						professionalMarket.value = products;
					}
				}
			} else {
				console.error('获取投资品数据失败:', response.msg || '未知错误');
				// 保持默认数据，不显示错误提示（因为有默认数据可用）
			}
		} catch (error) {
			console.error('获取投资品数据失败:', error);
			// 保持默认数据，网络错误时不显示提示（因为有默认数据可用）
		}
	};

	// 当前激活的市场标签
	const activeTab = ref('beginner');

	// 新手市场数据
	const beginnerMarket = ref([{
			name: 'Helmet #1005',
			coverImage: '/static/icon/bg5.png',
			progress: 49,
			limit: '100-500',
			profit: 1.5
		},
		{
			name: 'Helmet #1005',
			coverImage: '/static/icon/bg5.png',
			progress: 49,
			limit: '500-2000',
			profit: 3.0
		},
		{
			name: 'Helmet #1005',
			coverImage: '/static/icon/bg5.png',
			progress: 49,
			limit: '2000-5000',
			profit: 4.2
		}
	]);

	// 专业市场数据
	const professionalMarket = ref([{
			name: 'Helmet #1005',
			coverImage: '/static/icon/bg5.png',
			progress: 49,
			limit: '1M-3M',
			profit: 18
		},
		{
			name: 'Helmet #1005',
			coverImage: '/static/icon/bg5.png',
			progress: 49,
			limit: '3M-10M',
			profit: 27
		},
		{
			name: 'Helmet #1005',
			coverImage: '/static/icon/bg5.png',
			progress: 49,
			limit: '10M-50M',
			profit: 42
		}
	]);

	// 切换市场标签
	const switchTab = (tab) => {
		activeTab.value = tab;
		// 根据标签获取对应的投资品数据
		if (tab === 'beginner') {
			getProductsPage(1); // 新手市场 categoryId = 1
		} else if (tab === 'professional') {
			getProductsPage(2); // 专业市场 categoryId = 2
		}
	};

	// 页面加载时获取数据
	onMounted(() => {
		getProfitData();
		// 默认加载新手市场数据
		getProductsPage(1);
		// 也预加载专业市场数据
		getProductsPage(2);
	});
</script>

<style scoped lang="scss">
	.content-box {
		min-height: 100vh;
		background-color: #F5F6FA;
		padding-bottom: 180rpx;
		box-sizing: border-box;
		// padding: 31.40rpx 34.89rpx;

		// 顶部金额显示区域
		.header-section {
			background: linear-gradient(90deg, #1E88E5 0%, #13D8CA 100%);
			padding: 31.40rpx 52.33rpx;
			color: #FFFFFF;
			// margin-bottom: 30rpx;

			.title-row {
				display: flex;
				// justify-content: space-between;
				align-items: center;
				margin-bottom: 19.19rpx;

				.title {
					font-size: 34.89rpx;
					font-weight: 400;
					letter-spacing: 0rpx;
					line-height: 50.51rpx;
					color: rgba(255, 255, 255, 1);
				}

				.eye-toggle {
					width: 40rpx;
					height: 40rpx;
					margin-left: 12.14rpx;

					image {
						width: 100%;
						height: 100%;
						color: rgba(255, 255, 255, 1);
					}
				}
			}

			.amount-row {
				margin-bottom: 43.61rpx;

				.amount {
					font-size: 34.89rpx;
					font-weight: 700;
					letter-spacing: 0rpx;
					line-height: 50.51rpx;
					color: rgba(255, 255, 255, 1);
					margin-right: 10rpx;
				}

				.unit {
					font-size: 32rpx;
				}
			}

			.stats-row {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 0 94.19rpx;
				margin-bottom: 34.89rpx;

				.stat-item {
					display: flex;
					align-items: center;
					margin-right: 30rpx;

					.dot {
						width: 17.44rpx;
						height: 17.44rpx;
						opacity: 1;
						border-radius: 50%;
						margin-right: 10.47rpx;

						&.green {
							background-color: #FFEB3B;
						}

						&.orange {
							background-color: #FF9800;
						}
					}

					.stat-label {
						font-size: 24.42rpx;
						font-weight: 500;
						letter-spacing: 0rpx;
						line-height: 35.36rpx;
						color: rgba(255, 255, 255, 1);
						// margin-right: 10.47rpx;
						margin-right: 4rpx;
					}

					.stat-value {
						font-size: 24rpx;
					}
				}
			}
		}

		// 特点介绍区域
		.features-section {
			display: flex;
			justify-content: space-between;
			border-radius: 26.16rpx;
			background: rgba(255, 255, 255, 1);
			box-shadow: 6.98rpx 0rpx 17.44rpx rgba(176, 176, 176, 0.25);
			backdrop-filter: blur(6.98rpx);
			padding: 25.82rpx 68.54rpx 41.34rpx ;
			// margin: auto 52.33rpx;
			margin-bottom: -80rpx;

			.feature-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;

				.feature-icon {
					width: 120rpx;
					height: 120rpx;
				}

				.feature-text {
					font-size: 24.42rpx;
					font-weight: 400;
					line-height: 35.36rpx;
					color: rgba(51, 51, 51, 1);
					margin-top: -18rpx;
				}
			}
		}

		// 市场切换标签
		.market-tabs {
			display: flex;
			margin-bottom: 20rpx;
			// margin-top: 66.28rpx;
			margin-top: 114.88rpx; //+80rpx - 31.4rpx

			.tab-item {
				padding: 20rpx 0;
				font-size: 31.4rpx;
				font-weight: 500;
				color: rgba(143, 143, 143, 1);
				margin-right: 31.4rpx;
				margin-left: 43.61rpx;
				position: relative;

				// .bottom-border {
				// 	width: 69.77rpx;
				// 	height: 6.98rpx;
				// 	border: 6.98rpx solid rgba(2, 123, 217, 1);
				// 	border-radius: 1742.54rpx;
				// }
				&.active {
					font-weight: 500;
					line-height: 45.46rpx;
					color: rgba(0, 0, 0, 1);
				}

				&.active::after {
					content: '';
					position: absolute;
					left: 0;
					right: 0;
					bottom: 0;
					width: 69.77rpx;
					height: 6.98rpx;
					border-radius: 1742.54rpx;
					background: rgba(2, 123, 217, 1);
					margin: 0 auto;
					// padding-bottom: 7rpx;
				}
			}
		}

		// 市场列表
		.market-list {
			margin: 109.89rpx 31.40rpx;

			.market-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 92.45rpx;
		

				// 专业市场样式
				&.professional {
					.item-right {
						padding-right: 41.86rpx;

						.item-profit {
							font-size: 27.91rpx;
							font-weight: 500;
							letter-spacing: 0rpx;
							line-height: 40.42rpx;
							color: rgba(13, 179, 100, 1);
						}

						.item-arrow {
							width: 27.91rpx;
							height: 26.51rpx;

							image {
								width: 100%;
								height: 100%;
							}
						}
					}
				}

				.new-left {
					border-radius: 20.93rpx;
					background-color: #FFFFFF;
					box-shadow: 1.74rpx 1.74rpx 5.23rpx rgba(102, 102, 102, 0.25);
				}

				.item-left {
					display: flex;
					align-items: center;
					justify-content: space-between;
					padding: 10.46rpx 34.88rpx;


					.name-box {
						margin-right: 20.93rpx;

						.item-image {
							width: 141.29rpx;
							height: 141.29rpx;
							border-radius: 50%;
							margin-right: 20rpx;
							margin-top: -78.49rpx;
							// margin-top: -50rpx;
						}

						.item-name {
							font-size: 27.91rpx;
							font-weight: 400;
							color: rgba(51, 51, 51, 1);
							white-space: nowrap;
							overflow: hidden;
							text-overflow: ellipsis;
							max-width: 160rpx;
						}
					}



					.item-info {
						text-align: right;

						.progress-container {
							display: flex;
							align-items: center;
							margin-bottom: 10rpx;

							.progress-text {
								font-size: 24.42rpx;
								font-weight: 300;
								letter-spacing: 0rpx;
								line-height: 35.36rpx;
								color: rgba(0, 0, 0, 1);
								margin-right: 10rpx;
							}

							.progress-bar {
								width: 143rpx;
								flex: 2;
								height: 10rpx;
								background-color: #F5F5F5;
								border-radius: 5rpx;
								overflow: hidden;
								margin-right: 10rpx;

								.progress-fill {

									height: 100%;
									background: linear-gradient(90deg, #FFC300 0%, #DEB018 34.03%, #FF5733 65.97%, #FF5733 100%);
								}

								// 专业市场进度条颜色
								.professional .progress-fill {
									background: linear-gradient(90deg, #16C4A3 0%, #4AD6CF 34.72%, #129CCA 65.97%, #027BD9 100%);
								}
							}

							.progress-percent {
								font-size: 20.93rpx;
								font-weight: 300;
								letter-spacing: 0rpx;
								line-height: 30.32rpx;
								color: rgba(0, 0, 0, 1);
							}
						}

						.item-limit {
							font-size: 24.42rpx;
							font-weight: 300;
							letter-spacing: 0rpx;
							line-height: 35.36rpx;
							color: rgba(0, 0, 0, 1);
						}
					}
				}

				// 新手市场右边样式
				.new-right {
					// margin-left: 20.93rpx;
					padding: 24rpx 27.91rpx;
					border-radius: 20.93rpx;
					background: rgba(255, 255, 255, 1);
					box-shadow: 1.74rpx 1.74rpx 5.23rpx rgba(102, 102, 102, 0.25);
				}

				.item-right {
					display: flex;
					flex-direction: column;
					align-items: center;


					.item-profit {
						font-size: 27.91rpx;
						font-weight: 500;
						letter-spacing: 0rpx;
						color: rgba(13, 179, 100, 1);
						margin-bottom: 10rpx;

						&.positive {
							color: #00B464;
						}
					}

					.item-arrow {
						width: 19.25rpx;
						height: 27.35rpx;

						image {
							width: 100%;
							height: 100%;
						}
					}
				}


			}


		}
	}
</style>